const path = require("path");
const { exec } = require("child_process");
function pexec(arg) {
  return new Promise((resolve, reject) => {
    exec(arg, (error, stdout) => {
      if (error) {
        reject(error);
      } else {
        resolve(stdout);
      }
    });
  });
}
function resolveCommitLog(cid) {
  return pexec('git log --source').then(res => {
    let commitLog = cid
    try {
      const [,,,...rest] = res.split(cid)[1].split('commit ')[0].split(/[\r\n]/)
      commitLog = rest.filter(Boolean).join('\n').replace(/^\s*/, '').replace(/\s*$/, '')
    } catch (error) {
    }
    return commitLog
  })
}
async function getPm2Command(name) {
  let cmd = "restart";
  return pexec(`pm2 info ${name}`)
    .catch((err) => {
      cmd = "start";
    })
    .then(() => cmd);
}
async function startPm2Project(name, runPath) {
  const cmd = await getPm2Command(name);
  const fixRunPath = path.join(__dirname, '..', '..', runPath)
  await pexec(`pm2 ${cmd} ${fixRunPath} --name ${name}`);
}
module.exports.pexec = pexec;
module.exports.getPm2Command = getPm2Command;
module.exports.resolveCommitLog = resolveCommitLog;
module.exports.startPm2Project = startPm2Project;

